package dj.engine.screen;

import java.util.EnumSet;

import dj.engine.panel.Panel;
import dj.engine.util.Vec2f;
import dj.engine.util.Vec2i;

public class SquareAndSidebarsManager extends AbstractLayoutManager {

	public static final int CENTER=1<<0;
	public static final int LEFT=1<<1;
	public static final int RIGHT=1<<2;
	
	private enum Option
	{
		CENTER, LEFT, RIGHT
	}
	private Panel center;
	private Panel left;
	private Panel right;
	
	@Override
	public void add(Panel p) {
		add(p, CENTER);
	}

	@Override
	public void add(Panel p, int options) {
		if(isSet(CENTER, options))
		{
			center = p;
		}
		else if(isSet(LEFT, options))
		{
			left = p;
		}
		else if(isSet(RIGHT, options))
		{
			right = p;
		}
	}
	
	@Override
	public void add(Panel p, int options, Object... params) {
		// TODO Auto-generated method stub
		this.add(p, options);
	}
	
	public EnumSet<Option> toEnumSet(int options)
	{
		EnumSet<Option> optionsSet = EnumSet.noneOf(Option.class);
		if((CENTER & options) != 0)
		{
			optionsSet.add(Option.CENTER);
		}
		if((LEFT & options)!= 0)
		{
			optionsSet.add(Option.LEFT);
		}
		if((RIGHT & options) != 0)
		{
			optionsSet.add(Option.RIGHT);
		}
		return optionsSet;
	}

	public void onResize(Vec2i newSize)
	{
		int centerSize = Math.min(newSize.x,  newSize.y);
		boolean rightFree = (right == null);
		boolean leftFree = (left == null);
		center.onResize(new Vec2i(centerSize, centerSize));
		if(leftFree && rightFree || !(leftFree || rightFree))
		{
			int leftOffset = (newSize.x - centerSize)/2;
			int topOffset = newSize.y - centerSize;
			center.setPosition(new Vec2f(leftOffset, topOffset));
			if(!(leftFree || rightFree))
			{
				Vec2i marginSize = new Vec2i((newSize.x - centerSize)/2, newSize.y);
				left.setPosition(new Vec2f(0, 0));
				left.onResize(marginSize);
				right.setPosition(new Vec2f(centerSize + marginSize.x, 0));
				right.onResize(marginSize);
			}
		}
		else if(leftFree)
		{
			center.setPosition(new Vec2f(0,0));
			right.setPosition(new Vec2f(centerSize, 0));
			right.onResize(new Vec2i(newSize.x - centerSize, newSize.y));
		}
		else
		{
			center.setPosition(new Vec2f(newSize.x - centerSize,0));
			System.out.println("setting left position");
			left.setPosition(new Vec2f(0, 0));
			left.onResize(new Vec2i(newSize.x - centerSize, newSize.y));
		}
	}

	
}
